package com.elite.groovy.kh;

import com.elite.groovy.util.EliteBean;
import com.elite.groovy.util.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;


public class CMUtil {
    private static final Log log = LogFactory.getLog(CMUtil.class);
    private static final String log_Prefix = "自动同步CM模板-";

    public static String saveTemplat(EliteBean eliteBean, JdbcTemplate jt, JSONObject tempJson) {

        String id = "";

        try {
            id = KHUtil.GetSFJV(tempJson, "id");
            String accountId = KHUtil.GetSFJV(tempJson, "accountId");
            String facebookNamespaceId = KHUtil.GetSFJV(tempJson, "facebookNamespaceId");
            String templatName = KHUtil.GetSFJV(tempJson, "name");
            String facebookName = KHUtil.GetSFJV(tempJson, "facebookName");
            String category = KHUtil.GetSFJV(tempJson, "category");
            String rejectionReason = KHUtil.GetSFJV(tempJson, "rejectionReason");
            String headerSettings = KHUtil.GetSFJV(tempJson, "headerSettings");
            String settings = KHUtil.GetSFJV(tempJson, "settings");
            String languagesStatus = KHUtil.GetSFJV(tempJson, "languagesStatus");
            String isActive = KHUtil.GetSFJV(tempJson, "isActive");
            String isIncomplete = KHUtil.GetSFJV(tempJson, "isIncomplete");
            String isPending = KHUtil.GetSFJV(tempJson, "isPending");
            String isValidationRequested = KHUtil.GetSFJV(tempJson, "isValidationRequested");
            String rejectedOnUtc = KHUtil.GetSFJV(tempJson, "rejectedOnUtc");
            String cancelledOnUtc = KHUtil.GetSFJV(tempJson, "cancelledOnUtc");
            String deletedOnUtc = KHUtil.GetSFJV(tempJson, "deletedOnUtc");
            String fulfilledOnUtc = KHUtil.GetSFJV(tempJson, "fulfilledOnUtc");
            String updatedOnUtc = KHUtil.GetSFJV(tempJson, "updatedOnUtc");
            String createdOnUtc = KHUtil.GetSFJV(tempJson, "createdOnUtc");
            String entityStatus = KHUtil.GetSFJV(tempJson, "entityStatus");

            // 检查数据是否已经存在
            String selectExistSQL = "Select Rec_Guid From Cm_Templates Where Id = ?";
            List<Map<String, Object>> selectExistResult = jt.queryForList(selectExistSQL, id);
            log.debug(log_Prefix + "模板检查结果:" + selectExistResult.toString());

            // 数据库操作
            String Rec_Guid = "";
            if (selectExistResult.size() == 0) {
                Rec_Guid = KHUtil.getRandomString(36);
                String insertSQL = "Insert Into Cm_Templates (Rec_Guid, Id, Accountid, Facebooknamespaceid, Templatname, Facebookname, Category, Rejectionreason, Headersettings, Settings, Languagesstatus, Isactive, Isincomplete, Ispending, Isvalidationrequested, Rejectedonutc, Cancelledonutc, Deletedonutc, Fulfilledonutc, Updatedonutc, Createdonutc, Entitystatus, Sync_Time) Values (Uuid(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, Now())";
                int num = jt.update(insertSQL, id, accountId, facebookNamespaceId, templatName, facebookName, category, rejectionReason, headerSettings, settings, languagesStatus, isActive, isIncomplete, isPending, isValidationRequested, rejectedOnUtc, cancelledOnUtc, deletedOnUtc, fulfilledOnUtc, updatedOnUtc, createdOnUtc, entityStatus);
                log.debug(log_Prefix + "新增数据(" + templatName + ") 数量：" + num);
            } else {
                Rec_Guid = selectExistResult.get(0).get("Rec_Guid").toString();
                String updateSQL = "Update Cm_Templates Set Id = ?, Accountid = ?, Facebooknamespaceid = ?, Templatname = ?, Facebookname = ?, Category = ?, Rejectionreason = ?, Headersettings = ?, Settings = ?, Languagesstatus = ?, Isactive = ?, Isincomplete = ?, Ispending = ?, Isvalidationrequested = ?, Rejectedonutc = ?, Cancelledonutc = ?, Deletedonutc = ?, Fulfilledonutc = ?, Updatedonutc = ?, Createdonutc = ?, Entitystatus = ?, Sync_Time = Now() Where Rec_Guid = ?";
                int num = jt.update(updateSQL, id, accountId, facebookNamespaceId, templatName, facebookName, category, rejectionReason, headerSettings, settings, languagesStatus, isActive, isIncomplete, isPending, isValidationRequested, rejectedOnUtc, cancelledOnUtc, deletedOnUtc, fulfilledOnUtc, updatedOnUtc, createdOnUtc, entityStatus, Rec_Guid);
                log.debug(log_Prefix + "更新数据(" + templatName + ") 数量：" + num);
            }
        } catch (Exception e) {
            log.error(log_Prefix + "模板存储操作异常-", e);
        }

        return id;
    }


    public static String saveTemplatLang(EliteBean eliteBean, JdbcTemplate jt, JSONObject tempJson, String Templates_ID, String languageType) {

        String id = "";

        try {

            id = KHUtil.GetSFJV(tempJson, "id");
            String name = KHUtil.GetSFJV(tempJson, "name");
            String sampleRejection = KHUtil.GetSFJV(tempJson, "sampleRejection");
            String headerContent = KHUtil.GetSFJV(tempJson, "headerContent");
            String content = KHUtil.GetSFJV(tempJson, "content");
            String footerContent = KHUtil.GetSFJV(tempJson, "footerContent");
            String interactiveSettings = KHUtil.GetSFJV(tempJson, "interactiveSettings");
            String rejectionReason = KHUtil.GetSFJV(tempJson, "rejectionReason");
            String isActive = KHUtil.GetSFJV(tempJson, "isActive");
            String isIncomplete = KHUtil.GetSFJV(tempJson, "isIncomplete");
            String isPending = KHUtil.GetSFJV(tempJson, "isPending");
            String isValidationRequested = KHUtil.GetSFJV(tempJson, "isValidationRequested");
            String rejectedOnUtc = KHUtil.GetSFJV(tempJson, "rejectedOnUtc");
            String fulfilledOnUtc = KHUtil.GetSFJV(tempJson, "fulfilledOnUtc");
            String updatedOnUtc = KHUtil.GetSFJV(tempJson, "updatedOnUtc");
            String createdOnUtc = KHUtil.GetSFJV(tempJson, "createdOnUtc");
            String entityStatus = KHUtil.GetSFJV(tempJson, "entityStatus");

            // 检查数据是否已经存在
            String selectExistSQL = "Select Rec_Guid From Cm_Templates_Languages Where Templates_ID = ? And Languagetype = ? And Id = ?";
            List<Map<String, Object>> selectExistResult = jt.queryForList(selectExistSQL, Templates_ID, languageType, id);
            log.debug(log_Prefix + "模板检查结果:" + selectExistResult.toString());

            // 数据库操作
            if (selectExistResult.size() == 0) {
                String insertSQL = "Insert Into Cm_Templates_Languages (Rec_Guid, Templates_ID, Languagetype, Id, Samplerejection, Name, Headercontent, Content, Footercontent, Interactivesettings, Rejectionreason, Isactive, Isincomplete, Ispending, Isvalidationrequested, Rejectedonutc, Fulfilledonutc, Updatedonutc, Createdonutc, Entitystatus, Sync_Time) Values (Uuid(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, Now())";
                int num = jt.update(insertSQL, Templates_ID, languageType, id, sampleRejection, name, headerContent, content, footerContent, interactiveSettings, rejectionReason, isActive, isIncomplete, isPending, isValidationRequested, rejectedOnUtc, fulfilledOnUtc, updatedOnUtc, createdOnUtc, entityStatus);
                log.debug(log_Prefix + "新增数据(" + name + ") 数量：" + num);
            } else {
                String updateSQL = "Update Cm_Templates_Languages Set Languagetype = ?, Id = ?, Samplerejection = ?, Name = ?, Headercontent = ?, Content = ?, Footercontent = ?, Interactivesettings = ?, Rejectionreason = ?, Isactive = ?, Isincomplete = ?, Ispending = ?, Isvalidationrequested = ?, Rejectedonutc = ?, Fulfilledonutc = ?, Updatedonutc = ?, Createdonutc = ?, Entitystatus = ?, Del_Flag = 0, Sync_Time = Now() Where Rec_Guid = ?";
                int num = jt.update(updateSQL, languageType, id, sampleRejection, name, headerContent, content, footerContent, interactiveSettings, rejectionReason, isActive, isIncomplete, isPending, isValidationRequested, rejectedOnUtc, fulfilledOnUtc, updatedOnUtc, createdOnUtc, entityStatus, selectExistResult.get(0).get("Rec_Guid").toString());
                log.debug(log_Prefix + "更新数据(" + name + ") 数量：" + num);
            }
        } catch (Exception e) {
            log.error(log_Prefix + "模板存储操作异常-", e);
        }

        return id;
    }

    // 模板参数入库
    public static void saveVariableLang(EliteBean eliteBean, JdbcTemplate jt, JSONObject resultJson, String Templates_ID) {

        // 先全部更新为不可用
        String updateSQL = "Update Cm_Templates_Variable Set Del_Flag = 1 Where Templates_Id = ?";
        int num = jt.update(updateSQL, Templates_ID);
        log.debug(log_Prefix + "模板参数-先全部更新为不可用(" + Templates_ID + ") 数量：" + num);

        try {

            JSONArray tempArr = resultJson.getJSONObject("settings").getJSONArray("replacementFields");
            for (int i = 0; i < tempArr.size(); i++) {
                JSONObject tempJson = tempArr.getJSONObject(i);
                String id = KHUtil.GetSFJV(tempJson, "id");
                String name = KHUtil.GetSFJV(tempJson, "name");
                String index = KHUtil.GetSFJV(tempJson, "index");
                String type = KHUtil.GetSFJV(tempJson, "type");

                // 检查数据是否已经存在
                String selectExistSQL = "Select Rec_Guid From Cm_Templates_Variable Where Variable_Index = ? And Variable_Name = ? And Templates_Id = ?";
                List<Map<String, Object>> selectExistResult = jt.queryForList(selectExistSQL, index, name, Templates_ID);
                log.debug(log_Prefix + "模板参数检查结果:" + selectExistResult.toString());

                // 数据库操作
                if (selectExistResult.size() == 0) {
                    String insertSQL = "Insert Into Cm_Templates_Variable (Rec_Guid, Templates_Id, Variable_Id, Variable_Type, Variable_Index, Variable_Name, Variable_Desc, Color, Bgcolor, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, ?, ?, ?, ?, '#333', '#DEDEDE', Now(), 0)";
                    num = jt.update(insertSQL, Templates_ID, id, type, index, name, name);
                    log.debug(log_Prefix + "模板参数新增数据(" + name + ") 数量：" + num);
                } else {
                    String Rec_Guid = selectExistResult.get(0).get("Rec_Guid").toString();
                    updateSQL = "Update Cm_Templates_Variable Set Del_Flag = 0, Sync_Time = Now() Where Rec_Guid = ?";
                    num = jt.update(updateSQL, Rec_Guid);
                    log.debug(log_Prefix + "模板参数更新数据(" + name + ") 数量：" + num);
                }
            }

        } catch (Exception e) {
            log.error(log_Prefix + "模板参数存储操作异常-", e);
        }

    }

}